package com.spark.lola.controller.ser;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.entity.ser.SupervisorRemindLog;
import com.spark.lola.entity.sup.SupplierInfo;
import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.mapper.sup.SupplierInfoMapper;
import com.spark.lola.service.ser.SupervisorRemindLogService;
import com.spark.lola.service.sup.ISupplierInfoService;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.DataBeanUtils;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.controller.BaseController;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.wms.cache.CollectionCache;
import com.spark.lola.support.wms.configuration.WmsProperties;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dengyejun
 * @since 2020-04-24
 */
@RestController
@RequestMapping("/api/ser/supplier-info")
public class SerSupplierInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SerSupplierInfoController.class);
    @Autowired
    private SupplierInfoMapper currentMapper;
    @Autowired
    private ISupplierInfoService currentService;
    @Autowired
    private PortalServiceOpenApi portalServiceOpenApi;
    @Autowired
    private SupervisorRemindLogService supervisorRemindLogService;
    @Autowired
    private WmsProperties wmsProperties;

    @RequestMapping("/existNo")
    public ResponseBean existNo(@RequestParam String no, @RequestParam(value = "id", defaultValue = "0") Long id) {
        int count = currentMapper.existNo(id, no);
        return ResponseBean.success(null, count);
    }

    /**
     * 根据业务获取供应商 0-所有
     *
     * @param salesmanId
     * @return
     */
    @RequestMapping(value = "/map/{salesmanId}")
    public ResponseBean map(@PathVariable(value = "salesmanId") Long salesmanId,
                            @RequestParam("key") String key, @SessionAttribute ShiroUser shiroUser) {
        if (wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            salesmanId = shiroUser.getId();
        }
        return ResponseBean.success(currentService.selectMap(salesmanId, key));
    }

    @RequiresPermissions(value = "m5610")
    @RequestMapping(value = "/findBy", consumes = "application/json")
    public ResponseBean findBy(@RequestBody QueryParam<SupplierInfo> queryBean,
                               @SessionAttribute ShiroUser shiroUser) {
        // 当前管理员是否客服岗位
        if (wmsProperties.getService().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setKey("o.serviceId");
            queryCondition.setOper("=");
            queryCondition.setValue(shiroUser.getId());
            queryBean.getQueryList().add(queryCondition);
        }
        // bindQuery(queryBean,shiroUser,"salesmanId",portalServiceOpenApi.findUserIds(shiroUser));

        PageParam<SupplierInfo> pageParam = queryBean.toPageParam();
        IPage<SupplierInfo> page = currentMapper.page(pageParam.getPage(), pageParam.getEntityWrapper());
        page.getRecords().forEach(item -> {
            if (item.getSalesmanId() != null) {
                item.setSalesman(CollectionCache.employees.get(item.getSalesmanId()));
            }
            if (item.getServiceId() != null) {
                item.setService(CollectionCache.employees.get(item.getServiceId()));
            }
        });
        return ResponseBean.success(page);
    }

    @RequiresPermissions(value = "m5614")
    @RequestMapping(value = "/findInfo/{id}", method = RequestMethod.GET)
    public ResponseBean findInfo(@PathVariable Long id,
                                 @SessionAttribute ShiroUser shiroUser) {
        SupplierInfo model;
        if (id == 0) {
            model = new SupplierInfo();
            if (wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
                model.setSalesmanId(shiroUser.getId());
            }
            if (wmsProperties.getService().getDutyId().get(1).equals(shiroUser.getDutyId())) {
                model.setServiceId(shiroUser.getId());
            }
        } else {
            model = currentService.getById(id);
            QueryWrapper<SupervisorRemindLog> wrapper = new QueryWrapper<>();
            wrapper.select("*");
            wrapper.eq("supplier_id", model.getId());
            model.setSupervisorRemindLogList(supervisorRemindLogService.list(wrapper));
            if (model.getServiceId() != null) {
                model.setService(CollectionCache.employees.get(model.getServiceId()));
            }
            if (model.getSalesmanId() != null) {
                model.setSalesman(CollectionCache.employees.get(model.getSalesmanId()));
            }
        }
        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = {"m5611", "m5613"}, logical = Logical.OR)
    @RequestMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean save(@RequestBody SupplierInfo form, @SessionAttribute ShiroUser shiroUser) throws Exception {
        SupplierInfo model = new SupplierInfo();
        if (form.getId() != null) {
            // 禁止修改项 做空处理
            model = currentService.getById(form.getId());
        }
        DataBeanUtils.buildUpdateBean(model, form);
        currentService.saveOrUpdate(model);
        model.setSupervisorRemindLogList(form.getSupervisorRemindLogList());
        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = "m5615")
    @RequestMapping("/on")
    public ResponseBean on(@RequestParam String nos) {
        int count = currentService.updateUsedByIds(CommonConstant.Y, nos);
        return ResponseBean.success(null, count);
    }

    @RequiresPermissions(value = "m5619")
    @RequestMapping("/bindService")
    public ResponseBean bindService(@RequestBody JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        Long salesmanId = jsonObject.getLong("salesmanId");
        if (id == null || salesmanId == null) {
            return ResponseBean.error("参数为空");
        }
        SupplierInfo supplierInfo = currentService.getById(id);
        if (supplierInfo.getSalesmanId() != null) {
            return ResponseBean.error("已绑定，请解绑后操作");
        }
        SupplierInfo info = new SupplierInfo(id, salesmanId);
        info.setVersion(supplierInfo.getVersion());
        if (currentService.updateById(info)) {
            return ResponseBean.success();
        }
        return ResponseBean.error("绑定失败");
    }

    @RequiresPermissions(value = "m56191")
    @RequestMapping("/unBindService")
    public ResponseBean unBindService(@RequestBody JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        if (id == null) {
            return ResponseBean.error("参数为空");
        }
        SupplierInfo supplierInfo = currentService.getById(id);
        if (supplierInfo.getSalesmanId() == null) {
            return ResponseBean.error("未绑定业务员");
        }
//        ShiroUser shiroUser = CollectionCache.employees.get(supplierInfo.getSalesmanId());
//        if (!shiroUser.getDeptId().equals(wmsProperties.getService().getDeptId())) {
//            return ResponseBean.error("该供应商绑定为非客服人员，禁止操作");
//        }
        if (currentMapper.resetSalesman(id) != 0) {
            return ResponseBean.success();
        }
        return ResponseBean.error("解绑失败");
    }

    @RequiresPermissions(value = "m5617")
    @RequestMapping("/allotService")
    public ResponseBean allotService(@RequestBody JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        Long serviceId = jsonObject.getLong("serviceId");
        if (id == null || serviceId == null) {
            return ResponseBean.error("参数为空");
        }
        SupplierInfo supplierInfo = currentService.getById(id);
        if (supplierInfo.getServiceId() != null) {
            return ResponseBean.error("已分配客服，请解除后操作");
        }
        SupplierInfo info = new SupplierInfo(id, serviceId, supplierInfo.getVersion());
        if (currentService.updateById(info)) {
            return ResponseBean.success();
        }
        return ResponseBean.error("分配失败");
    }

    @RequiresPermissions(value = "m5618")
    @RequestMapping("/unAllotService")
    public ResponseBean unAllotService(@RequestBody JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        if (id == null) {
            return ResponseBean.error("参数为空");
        }
        SupplierInfo supplierInfo = currentService.getById(id);
        if (supplierInfo.getServiceId() == null) {
            return ResponseBean.error("未分配客服");
        }
        if (currentMapper.resetService(id) != 0) {
            return ResponseBean.success();
        }
        return ResponseBean.error("解除失败");
    }

    @RequiresPermissions(value = "m5616")
    @RequestMapping("/un")
    public ResponseBean un(@RequestParam String nos) {
        int count = currentMapper.updateUsedByIds(CommonConstant.N, nos);
        return ResponseBean.success(null, count);
    }

    @RequiresPermissions(value = "m5612")
    @RequestMapping("/del")
    public ResponseBean del(@RequestParam(value = "nos") List<Long> ids) {
        ids.forEach(id -> {
            currentService.removeById(id);
        });
        return ResponseBean.success();
    }
}
